﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MugenInjection.Infrastructure;
using MugenInjection.Interface;

namespace MugenInjection.Web.Mvc
{
    /// <summary>
    ///     Dependency resolver implementation for mugen injection.
    /// </summary>
    public sealed class MugenInjectionDependencyResolver : IDependencyResolver
    {
        #region Fields

        private readonly IInjector _injector;

        #endregion

        #region Constructors

        /// <summary>
        ///     Initializes a new instance of the <see cref="MugenInjectionDependencyResolver" /> class.
        /// </summary>
        public MugenInjectionDependencyResolver(IInjector injector)
        {
            Validate.ArgumentNotNull(injector, "injector");
            _injector = injector;
        }

        #endregion

        #region Implementation of IDependencyResolver

        /// <summary>
        ///     Resolves singly registered services that support arbitrary object creation.
        /// </summary>
        /// <returns>
        ///     The requested service or object.
        /// </returns>
        /// <param name="serviceType">The type of the requested service or object.</param>
        public object GetService(Type serviceType)
        {
            object result;
            _injector.TryGet(serviceType, out result);
            return result;
        }

        /// <summary>
        ///     Resolves multiply registered services.
        /// </summary>
        /// <returns>
        ///     The requested services.
        /// </returns>
        /// <param name="serviceType">The type of the requested services.</param>
        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (_injector.CanResolve(serviceType, true, false))
                return _injector.GetAll(serviceType).ToList();
            return InjectorUtilsInternal.EmptyParams;
        }

        #endregion
    }
}